package service

import (
	"fmt"
	"gin-vue-admin/global"
	"gin-vue-admin/model"
	"gin-vue-admin/model/request"
	"strconv"
)

//@author: [piexlmax](https://github.com/piexlmax)
//@function: CreateGoodsOrder
//@description: 创建GoodsOrder记录
//@param: goodsOrder model.GoodsOrder
//@return: err error

func CreateGoodsOrder(goodsOrder model.GoodsOrder) (err error) {
	id, err := GetLastGoodsID()
	if err != nil {
		goodsOrder.SelectGoodsId = model.GoodsIdPrefix + 1
	}else{
		goodsOrder.SelectGoodsId = id + 1
	}
	if goodsOrder.LogisticsNumber == ""{
		goodsOrder.GoodsOrderState = "待下单"
	}else{
		goodsOrder.GoodsOrderState = "运送中"
	}
	goodsOrder.GoodsRelateBill = ""
	err = global.GVA_DB.Create(&goodsOrder).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: DeleteGoodsOrder
//@description: 删除GoodsOrder记录
//@param: goodsOrder model.GoodsOrder
//@return: err error
func DeleteGoodsOrder(goodsOrder model.GoodsOrder) (err error) {
	err = global.GVA_DB.Delete(&goodsOrder).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: DeleteGoodsOrderByIds
//@description: 批量删除GoodsOrder记录
//@param: ids request.IdsReq
//@return: err error

func DeleteGoodsOrderByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]model.GoodsOrder{},"id in ?",ids.Ids).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: UpdateGoodsOrder
//@description: 更新GoodsOrder记录
//@param: goodsOrder *model.GoodsOrder
//@return: err error

func UpdateGoodsOrder(goodsOrder model.GoodsOrder) (err error) {
	state, _ := GetGoodsState(goodsOrder.SelectGoodsId)
	if goodsOrder.LogisticsNumber != "" && state == "待下单"{
		goodsOrder.GoodsOrderState = "运送中"
	}
	err = global.GVA_DB.Save(&goodsOrder).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetGoodsOrder
//@description: 根据id获取GoodsOrder记录
//@param: id uint
//@return: err error, goodsOrder model.GoodsOrder

func GetGoodsOrder(id uint) (err error, goodsOrder model.GoodsOrder) {
	err = global.GVA_DB.Where("id = ?", id).First(&goodsOrder).Error
	return
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetGoodsOrderInfoList
//@description: 分页获取GoodsOrder记录
//@param: info request.GoodsOrderSearch
//@return: err error, list interface{}, total int64
func GetGoodsOrderInfoList(info request.GoodsOrderSearch) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Model(&model.GoodsOrder{})
    var goodsOrders []model.GoodsOrder
    // 如果有条件搜索 下方会自动创建搜索语句
	if info.GoodsName != ""{
		db = db.Where("goods_name LIKE ?", "%"+info.GoodsName+"%")
	}
	if info.GoodsOrderOwner != ""{
		db = db.Where("goods_order_owner = ?", info.GoodsOrderOwner)
	}
	if info.CategorySecond != ""{
		db = db.Where("category_second = ?", info.CategorySecond)
	}
	if info.GoodsOrderState != ""{
		db = db.Where("goods_order_state = ?", info.GoodsOrderState)
	}
	err = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Find(&goodsOrders).Error
	return err, goodsOrders, total
}

func GetDeliveryGoodsOrderInfoList(info request.GoodsOrderSearch) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&model.GoodsOrder{})
	var goodsOrders []model.GoodsOrder
	// 如果有条件搜索 下方会自动创建搜索语句
	db = db.Where("goods_order_state = ?", "运送中")
	err = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Find(&goodsOrders).Error
	return err, goodsOrders, total
}

func GetGoodsOrderInfoById(id string) (err error, list model.GoodsOrder) {
	var goodsOrder model.GoodsOrder
	// 如果有条件搜索 下方会自动创建搜索语句
	err = global.GVA_DB.Model(&model.GoodsOrder{}).Where("select_goods_id = ?", id).First(&goodsOrder).Error
	return err, goodsOrder
}

/**
	获取最新的任务ID
*/
func GetLastGoodsID() (int, error) {
	var goodsOrderM model.GoodsOrder
	db := global.GVA_DB.Model(&model.GoodsOrder{})
	err := db.Last(&goodsOrderM).Error
	return goodsOrderM.SelectGoodsId, err
}

func GetGoodsState(goodsId int) (string, error) {
	var goodsOrderM model.GoodsOrder
	db := global.GVA_DB.Model(&model.GoodsOrder{})
	err := db.Where("select_goods_id = ?", goodsId).First(&goodsOrderM).Error
	return goodsOrderM.GoodsOrderState, err
}

// 生成财务单
func CreateRelateBill(goodsOrderId string) error {
	var goodsOrder model.GoodsOrder
	err := global.GVA_DB.Where("select_goods_id = ?", goodsOrderId).First(&goodsOrder).Error
	if err != nil{
		return err
	}else{
		_, goodsOrder := GetGoodsOrderInfoById(goodsOrderId)
		if goodsOrder.GoodsRelateBill != "" {
			return fmt.Errorf("对应账单已存在，无法重复创建")
		}else{
			var billInfo model.BillList
			billInfo.BillAmount = goodsOrder.PurchasePrice * float64(goodsOrder.GoodsCount) + goodsOrder.DeliveryAmount
			billInfo.BillOperator = goodsOrder.GoodsOrderOwner
			billInfo.BillUseFor = "进货"
			billInfo.BillRelateGoodsOrderId,_ = strconv.Atoi(goodsOrderId)
			billInfo.BillRelateGoodsOrder = goodsOrder.GoodsName
			billInfo.BillRemarks = "单号【" + strconv.Itoa(goodsOrder.SelectGoodsId) +"】，" +
				"标题【" + goodsOrder.GoodsName +"】，" +
				"数量【" + strconv.Itoa(goodsOrder.GoodsCount) + "】, " +
				"单价【" + strconv.FormatFloat(goodsOrder.PurchasePrice, 'f', -1,64)+"】"
			err, billId := CreateBillList(billInfo)
			if err != nil{
				return err
			}else{
				db := global.GVA_DB.Model(&model.GoodsOrder{})
				err = db.Where("select_goods_id = ?", goodsOrderId).First(&goodsOrder).Update(
					"goods_relate_bill", billId).Error
				return err
			}
		}
	}
}


//func CreateRelateBill(billInfo model.BillInfo) error {
//	_, goodsOrder := GetGoodsOrderInfoById(strconv.Itoa(billInfo.GoodsOrderId))
//	if goodsOrder.GoodsRelateBill != "" {
//		return fmt.Errorf("对应账单已存在，无法重复创建")
//	}else{
//		err, billId := CreateBillList(billInfo.BillList)
//		global.GVA_LOG.Error("创建bill", zap.Any("billId", billId))
//		if err != nil{
//			global.GVA_LOG.Error("创建bill失败", zap.Any("err", err))
//			return err
//		}else{
//			global.GVA_LOG.Error("创建bill成功", zap.Any("err", err))
//			db := global.GVA_DB.Model(&model.GoodsOrder{})
//			var goodsOrder model.GoodsOrder
//			err = db.Where("select_goods_id = ?", billInfo.GoodsOrderId).First(&goodsOrder).Update(
//				"goods_relate_bill", billId).Error
//			return err
//		}
//	}
//}

func SetStateStorage(goodsOrderId string) (err error) {
	err = global.GVA_DB.Where("select_goods_id = ?", goodsOrderId).First(&model.GoodsOrder{}).Update(
		"goods_order_state", "已入库").Error
	return err
}

